package com.springboot.logback.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * neu
 * 2019/7/29 9:45
 *
 * @Version : 1.0
 * @Description :
 */
public class LoggerManager {

    private static ILoggerFactory factory;

    static {
        // 配置文件解析
        factory = initFactoryConfig();
    }

    private static ILoggerFactory initFactoryConfig() {
        String confClass = null;
        InputStream is = null;
        is = LoggerManager.class.getResourceAsStream("logbackconfig.perproties");
        if(null == is){
            is =  LoggerManager.class.getResourceAsStream("/logbackconfig.perproties");
        }
        if(null != is){
            confClass = getConfClass(is);
        }
        factory = createFactory(confClass);
        closeStream(is);
        return factory;
    }

    private static ILoggerFactory createFactory(String confClass) {
        Class<?> aClass;
        try {
            aClass = Class.forName(confClass);
            factory = (ILoggerFactory) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("无法实例化logbackconfig.perproties中配置的日志工厂，[" + confClass + "]不存在");
            System.out.println("使用默认配置启动");
        }
        return factory;
    }

    private static void closeStream(InputStream inputStream) {
        try{
            if(null != inputStream)
                inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static String getConfClass(InputStream is) {
        String confClass = null;
        Properties properties = new Properties();
        try {
            properties.load(is);
            confClass = StringUtils.isNotBlank(properties.getProperty("LoggingFactory")) ? properties.getProperty("LoggingFactory").trim():null;
            return confClass;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  confClass;
    }

    // 根据配置读取factory，从factory返回ILogger
    public static ILogger getLogger(String name) {
        return factory.getLogger(name);
    }

    /**
     * 重载方法
     * @author
     * @param %param
     *  name% %param description%
     * @return
     */
    public static ILogger getLogger(Class<?> clazz) {
        return factory.getLogger(clazz);
    }

}
